//上厅堂商品页
var counteventtimes = [];
var app = getApp();
var server = require('../../utils/server');
var common = require('../../utils/common');
var newMedalList = [];
var productData = [];
Page({
  data: {
    userAvatar: '',
    userName: '',
    vipInfo: '',
    medalPercent: 0,
    timestamp: (Date.parse(new Date())),
    chefGoodsList: [],
    memberimgUrls: [],
    nearestMedalInfo: [],
    isShowMedalPop: false,
    isShowBannerPop: false,
    curFrName: '',
    curBannerImg: '',
    curSecName: '',
    curBannerDesc: '',
    curMedalName: '',
    curMedalImg: '',
    curMedalDesc: '',
    curMedalStatus: '',
    goodProducts: [{
      "name": '尖端食材',
      "desc": '资深全球买手为你挑选尖端食材',
      "secname": '私享总监买手选货',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon1.png'
    }, {
      "name": '新品尝鲜',
      "desc": '每月皆有新品，轻松吃遍头鲜',
      "secname": '当季好货抢先尝',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon2.png'
    }, {
      "name": '内购资格',
      "desc": '详询您的专属客服可获得更多信息',
      "secname": '员工内购同款同价',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon3.png'
    }],
    benefitsList: [{
      "name": '下单送调味食材',
      "desc": ' 根据主厨推荐菜单，赠送葱姜蒜等调味食材',
      "secname": '无需买菜 每单1次',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon4.png'
    }, {
      "name": '下单送菜',
      "desc": '肉禽海鲜生鲜产品，下单即送绿叶菜一份',
      "secname": '根据订单免费搭配',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon5.png'
    }, {
      "name": '运费券',
      "desc": '不定期发放',
      "secname": '不定期发放',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon6.png'
    }],
    payServices: [{
      "name": '专车专送',
      "desc": '按你指定时间进行专线配送',
      "secname": '包车专为你送',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon7.png',
      "price": '80元/次'
    }, {
      "name": '生鲜分切',
      "desc": '肉禽海鲜生鲜产品，可安排需求进行分切（是否能满足分切以服务大使确认为准）',
      "secname": '按需加工',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon8.png',
      "price": '20元/次'
    }, {
      "name": '定期配',
      "secname": '米面粮油定期到家',
      "desc": '服务权益开发中',
      'pic_url': 'http://static.sungivenfood.com/xcx/stt/icon9.png',
      "price": ''
    }],
    scrollIndex: 0,
    isShowNewMedalPop: false,
    curNewMedalImg: '',
    curNewMedalName: '',
    curMedalDesc: '',
    logoMtop: 20,
    isShowHome: false,
    menuBtnBottom: 58,
    isGetRedpacket: false,
    showRedPacketsClose: false
  },
  onHide() {
    if(this.data.memberimgUrls.length>0){
      for (var i = 0; i < this.data.memberimgUrls.length; i++) {
        for (var j = 0; j < this.data.memberimgUrls[i].list.length; j++) {
          console.log('onhide')
          clearTimeout(counteventtimes[this.data.memberimgUrls[i].event_id][j]);
          counteventtimes[this.data.memberimgUrls[i].event_id][j] = 0
        }
      }
    }
  },
  onUnload(){
    console.log('onunload')
    if(this.data.memberimgUrls.length>0){
      for (var i = 0; i < this.data.memberimgUrls.length; i++) {
        for (var j = 0; j < this.data.memberimgUrls[i].list.length; j++) {
          console.log('onunload')
          clearTimeout(counteventtimes[this.data.memberimgUrls[i].event_id][j]);
          counteventtimes[this.data.memberimgUrls[i].event_id][j] = 0
        }
      }
    }
  },
  onShow() {
    this.setData({
      isShowHome: getCurrentPages().length == 1 ? true : false
    })
    if (app.globalData.sdkversion > 210 && app.globalData.sdkversion != 1997 && app.globalData.sdkversion != 1991) {
      console.log(wx.getMenuButtonBoundingClientRect())
      this.setData({
        logoMtop: wx.getMenuButtonBoundingClientRect().top == 0 ? 20 : wx.getMenuButtonBoundingClientRect().top,
        menuBtnBottom: wx.getMenuButtonBoundingClientRect().bottom == 0 ? 58 : wx.getMenuButtonBoundingClientRect().bottom,
        menuBtnHeight: wx.getMenuButtonBoundingClientRect().height == 0 ? 32 : wx.getMenuButtonBoundingClientRect().height
      })
    }
    wx.getStorage({
      key: 'userInfo',
      success: res => {
        this.setData({
          userAvatar: res.data.avatar,
          userName: res.data.nickname
        })
        this.getVipInfo();
      },
      fail: res => {
        wx.navigateTo({
          url: 'productListsM4',
        })
      }
    })
  },
  getVipInfo() {
    server.postJSON(common.basePath + 'vip/info/', '', res => {
      if (res.data.errno == '0') {
        let data = res.data.data;
        this.setData({
          vipInfo: data,
          medalPercent: (data.medal_num_has / data.medal_num_all) * 100
        })
        if (data.medal.length > 0) {
          this.setData({
            nearestMedalInfo: data.medal[data.medal.length - 1]
          })
        }
        newMedalList = data.medal.filter((item, index) => {
          return item.show_time == '0';
        })
        if (newMedalList.length > 0) {
          this.data.curNewMedalIndex = 0;
          this.setData({
            isShowNewMedalPop: true,
            curNewMedalImg: newMedalList[0].pic_url_big,
            curNewMedalName: newMedalList[0].name,
            curNewMedalDesc: newMedalList[0].desc,
            curNewMedalId: newMedalList[0].medal_id
          })
        }
        console.log(newMedalList)
        wx.stopPullDownRefresh();
        this.getChefEventLists();
        this.getCurSeasonPro();
        this.getAdBanner();
      } else {
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  getAdBanner() {
    server.postJSON(common.storePath + 'advert/getvipbanner/', '', res => {
      var res = res.data;
      if (res.errno == "0") {
        wx.hideNavigationBarLoading();
        common.hideLoading();
        this.setData({
          adBannerList: res.data
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  goToUrl(e) {
    var curtarget = e.currentTarget.dataset;
    var result = [];
    if (curtarget.appid != "" && curtarget.pathurl != "") { //跳转小程序
      console.log(curtarget.pathurl)
      wx.navigateToMiniProgram({
        appId: curtarget.appid,
        path: curtarget.pathurl,
        success: res => {
          console.log("成功打开!")
        },
        fail: res => {}
      })
    } else if (curtarget.appid == "" && curtarget.pathurl != "") { //跳转公众号文章
      console.log(curtarget.pathurl)
      this.data.curPath = curtarget.pathurl;
      wx.navigateTo({
        url: '../../pages/common/gzh?url=' + encodeURIComponent(curtarget.pathurl),
      })
    } else { //跳转小程序内部页面
      this.data.curPath = curtarget.path;
      this.data.curPathName = curtarget.name;
      console.log(this.data.curPathName)
      var path = curtarget.path;
      if (path.indexOf('url') > -1) {
        console.log(path.split("url=")[1])
        wx.navigateTo({
          url: path.split("url=")[1],
        })
      } else if (path.indexOf('store') > -1) {
        if (path.indexOf('store_category') > -1) {
          var query = path.split("?")[1];
          console.log(query);
          wx.navigateTo({
            url: '../../pages/shop/productsListIndex?' + query,
          })
        } else {
          wx.navigateTo({
            url: '../../pages/shop/productsListIndex',
          })
        }
      }
    }
  },
  getCurSeasonPro() {
    server.login(common.storePath + 'event/listvip/', {
      "city": app.globalData.city
    }, res => {
      if (res.data.errno == "0") {
        productData = res.data.data;
        if (productData.length > 0) {
          for (var i = 0; i < productData.length; i++) {
            if (productData[i].list.length > 0) {
              for (var j = 0; j < productData[i].list.length; j++) {
                productData[i].list[j].counttime = '00:00:00';
                if (productData[i].list[j].status == 'going') {
                  this.countEventTime(i, j)
                }
              }
            }
          }
        }

      } else {
        common.showErrorToast(res.data.errmsg);
      }
    })
  },
  getChefEventLists() {
    server.postJSON(common.storePath + 'event/hotGoods/', '', res => {
      var res = res.data;
      if (res.errno == "0") {
        wx.hideNavigationBarLoading();
        common.hideLoading();
        this.setData({
          eventDetail: res.data.event,
          chefGoodsList: res.data.goods
        })
      } else {
        common.showErrorToast(res.errmsg)
      }
    })
  },
  // 会员专供倒计时
  countEventTime(frindex, secindex) {
    console.log('counttime', 2121)
    var that = this;
    var stime = Date.parse(new Date()) / 1000,
      id = productData[frindex].event_id,
      endtime = productData[frindex].list[secindex].end_time,
      status = productData[frindex].list[secindex].status,
      frindex = frindex,
      secindex = secindex;
    var leftTime = endtime - stime;
    var d, h, m, s;
    d = Math.floor(leftTime / 60 / 60 / 24);
    !counteventtimes[id] && (counteventtimes[id] = [])
    counteventtimes[id][secindex] && clearTimeout(counteventtimes[id][secindex])
    if (leftTime > 0) {
      h = d * 24 + Math.floor(leftTime / 60 / 60 % 24);
      m = Math.floor(leftTime / 60 % 60);
      s = Math.floor(leftTime % 60);
      productData[frindex].list[secindex].percent = (((Date.parse(new Date()) / 1000 - productData[frindex].list[secindex].start_time) / (productData[frindex].list[secindex].end_time - productData[frindex].list[secindex].start_time)).toFixed(2)) * 100;
      this.setData({
        memberimgUrls: productData
      })
      counteventtimes[id][secindex] = setTimeout(function () {
        that.countEventTime(frindex, secindex);
      }, 1000);
    } else if (leftTime <= 0) {
      if (status == 'going') {
        h = 0;
        m = 0;
        s = 0;
      } else {
        h = 0;
        m = 0;
        s = 0;
      }
    }
    h = checkTime(h);
    m = checkTime(m);
    s = checkTime(s);

    function checkTime(i) {
      if (i < 10) {
        i = "0" + i;
      }
      return i;
    }
    if (d <= 0) {
      productData[frindex].list[secindex].counttime = h + ':' + m + ':' + s;
      this.setData({
        memberimgUrls: productData
      })
    } else {
      productData[frindex].list[secindex].counttime = d + '天';
      this.setData({
        memberimgUrls: productData
      })
    }

  },
  scrollBanner(e) {
    console.log(e)
    var scrollLeft = e.detail.scrollLeft;
    this.setData({
      scrollIndex: parseInt(scrollLeft / 317)
    })
    console.log(this.data.scrollIndex)
  },
  goToIndex() {
    wx.switchTab({
      url: '../../pages/index/index',
    })
  },
  goToCart() {
    app.globalData.cartIndexType = 1;
    wx.switchTab({
      url: '../../pages/cart/cartIndex',
    })
  },
  goToOrder() {
    wx.switchTab({
      url: '../../pages/order/orderIndex',
    })
  },
  goToUserCenter() {
    wx.switchTab({
      url: '../../pages/user_center/userinfoIndex',
    })
  },
  goToCardLists() {
    wx.navigateTo({
      url: '../../pages/memberCard/ycCards',
    })
  },
  goToVouchers() {
    wx.navigateTo({
      url: '../../pages/user_center/userVouchers?isvip=1',
    })
  },
  //会员专供详情
  goToEventDetail(e) {
    var evendId = e.currentTarget.dataset.id,
      template_id = e.currentTarget.dataset.templateid,
      goodsid = e.currentTarget.dataset.goodsid;
    if (template_id != '0') {
      wx.navigateTo({
        url: 'productListsM' + template_id + '?eventid=' + evendId
      })
    } else {
      wx.navigateTo({
        url: 'productDetailM?eventid=' + evendId + '&&goodsid=' + goodsid
      })
    }
  },
  goToProductDetail(e) {
    wx.navigateTo({
      url: 'productDetailM?eventid=' + e.currentTarget.dataset.id + '&&goodsid=' + e.currentTarget.dataset.goodsid,
    })
  },
  showBannerPop(e) {
    var currentTarget = e.currentTarget.dataset;
    this.setData({
      curFrName: currentTarget.name,
      curBannerImg: currentTarget.img,
      curSecName: currentTarget.secname,
      curBannerDesc: currentTarget.desc,
      isShowBannerPop: true
    })
  },
  hideBannerPop() {
    this.setData({
      isShowBannerPop: false
    })
  },
  showMedalPop(e) {
    var currentTarget = e.currentTarget.dataset;
    this.setData({
      curMedalName: currentTarget.name,
      curMedalImg: currentTarget.img,
      curMedalDesc: currentTarget.desc,
      curMedalStatus: currentTarget.status,
      curMedalGettime: currentTarget.gettime,
      isShowMedalPop: true
    })
  },
  hideMedalPop() {
    this.setData({
      isShowMedalPop: false
    })
  },
  onPullDownRefresh() {
    this.getVipInfo();
  },
  openPacketsList() {
    this.setData({
      showRedPackets: true,
      showRedPacketsClose: false
    })
  },
  checkRedPackage() {
    console.log(121)
    this.setData({
      isGetRedpacket: true
    })
    server.postJSON(common.basePath + 'vip/medal/', {
      "medal_id": this.data.curNewMedalId
    }, res => {
      this.setData({
        isGetRedpacket: false
      })
      if (res.data.errno == '0') {
        wx.hideLoading();
        if (res.data.data.coupon_list.length > 0) {
          this.setData({
            showRedPacketsClose: true,
            hbLists: res.data.data.coupon_list,
            isShowNewMedalPop: false
          })
        } else {
          this.showNextNewMedal();
        }
      } else {
        this.setData({
          isShowNewMedalPop: false
        })
        common.showErrorToast(res.data.errmsg)
      }
    })
  },
  showNextNewMedal() {
    this.setData({
      showRedPackets: false,
      showRedPacketsClose: false
    })
    console.log(newMedalList, this.data.curNewMedalIndex, newMedalList.length)
    if (this.data.curNewMedalIndex < newMedalList.length - 1) {
      this.data.curNewMedalIndex += 1;
      this.setData({
        isShowNewMedalPop: true,
        curNewMedalImg: newMedalList[this.data.curNewMedalIndex].pic_url_big,
        curNewMedalName: newMedalList[this.data.curNewMedalIndex].name,
        curNewMedalDesc: newMedalList[this.data.curNewMedalIndex].desc,
        curNewMedalId: newMedalList[this.data.curNewMedalIndex].medal_id
      })
    } else {
      this.setData({
        isShowNewMedalPop: false
      })
    }
  },
  goToIndex() {
    if (this.data.isShowHome) {
      wx.switchTab({
        url: '../../pages/index/index'
      })
    } else {
      wx.navigateBack()
    }
  }
})